/*
* Author: Sowmya Kameswaran
*/
package com.foo.SnapshotData;

import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.foo.Entity.HistoricalData;
import com.foo.TextDataSender.DataSender;


/**
 * Session Bean implementation class SnapshotDataProvider
 */
@Stateless(name="SnapshotDataProvider")
public class SnapshotDataProvider implements SnapshotDataProviderRemote, SnapshotDataProviderLocal {

	@PersistenceContext(unitName="snapshotinformationprovider") // This is the entity manager required by the Entity bean
	private EntityManager em;

	int total =0 ;
	Query getdatabytime = null;
	List<HistoricalData> snapshotdatalist = null;
	String snapshotmessage="";
	DataSender datasender = new DataSender();
	/**
	 * Default constructor. 
	 */
	public SnapshotDataProvider() 
	{
		/*try
		{
			Properties properties = new Properties();
			properties.put(Context.PROVIDER_URL, "jnp://localhost:1099");
			properties.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
			properties.put(Context.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
			Context ctx = new InitialContext(properties);
			Object ref = ctx.lookup("DataSender/remote");
			datasender = (DataSenderRemote) PortableRemoteObject.narrow(ref, DataSenderRemote.class);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}*/

		System.out.println("In server class to retrieve data \n"); 
	}

	
	@Override
	public void sendsnapshotinfo(String sorttype,String paramname,Date fromdate,Date todate)
	{
		 System.out.println("Entering server function Snapshot Data with parameters " +sorttype + " " +paramname + " "+fromdate + " " +todate);
	
			snapshotmessage="";
			getdatabytime = em.createQuery("from HistoricalData d where d.ticker_symbol = :ticker_symbol and d.deals_date between :fromdate and :todate");
			getdatabytime.setParameter("ticker_symbol", sorttype );
			getdatabytime.setParameter("fromdate",fromdate );
			getdatabytime.setParameter("todate",todate );

			System.out.println("The query : " + getdatabytime.toString());
			snapshotdatalist=getdatabytime.getResultList();
			int listsize = snapshotdatalist.size();
			System.out.println("list size "+listsize);

			for(int k=0;k<listsize;k++)
			{
				System.out.println("Inside for loop of snapshot data \n");
				snapshotmessage += snapshotdatalist.get(k).getTicker_symbol()+","+snapshotdatalist.get(k).getDeals_date().toString()+","+snapshotdatalist.get(k).getOpen_value()+","+snapshotdatalist.get(k).getHigh_value()
				+","+snapshotdatalist.get(k).getLow_value()+","+snapshotdatalist.get(k).getClose_value()+","+snapshotdatalist.get(k).getVolume()+",";
			}
			
		System.out.println("The message " +snapshotmessage);
		datasender.sendMessage("Snapshot",snapshotmessage);

	}
	
}
